home *** CD-ROM | disk | FTP | other *** search
- Path: li.net!jeremy
- From: jeremy@newshost.li.net (Jeremy Markman)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: 4 Apr 1996 14:51:43 GMT
- Organization: LI Net (Long Island Network)
- Message-ID: <4k0nlv$hn6@linet06.li.net>
- References: <31624BC2.70D2@sooner.net>
- NNTP-Posting-Host: linet04.li.net
- X-Newsreader: TIN [version 1.2 PL2]
-
- Eddie Bush (edwbush@sooner.net) wrote:
- : I am trying to construct a C function that will recursively convert
- : a string such as "1234" into it's integer equivelant (1234).
- : 2)the function should be called with a character pointer:
- : Such as: convert("1234");
- : making the prototype look something like:
- : int convert(char *p);
-
- This is just off the top of my head:
-
- int convert(char *string)
- {
- int value;
- int len = strlen(string);
-
- if (string[0] == '\0')
- return(0);
- value = convert(string + 1);
- if (len == 1)
- value += string[0] - 1;
- else
- {
- value /= 10 * (len - 1);
- value += string[0] - '0';
- value *= 10 * (len - 1);
- }
- return(value);
- }
-
- If you were to use a loop instead of recursion, the code may be slightly
- smaller:
-
- int convert(char *string)
- {
- int value = 0;
- int i = 0;
-
- while (string[i] != '\0')
- {
- value = value * 10 + string[i] - '0';
- i++;
- }
- return(value);
- }
-
- Theory time:
-
- When parsing a string from left to right, you can convert the string to a
- number without having to know how long the string is. You just multiply
- the current value by 10, then add the next character:
- "1234"
- 0 * 10 + 1 = 1
- 1 * 10 + 2 = 12
- 12 * 10 + 3 = 123
- 123 * 10 + 4 = 1234
-
- But when using recursion, you actually are parsing the string from right
- to left, so you need to know how long the CURRENT string is. What I've
- done is divide the current value by some multiple of 10 so that the ones
- digit becomes zero...Then, add the next digit, then multiply the new
- value by that same multiple of 10, and you have the number...
- To wit:
-
- 0 + 4 = 4
- 4 / 10 * 1 = .4 | .4 + 3 = 3.4 | 3.4 * 10 * 1 = 34
- 34 / 10 * 2 = .34 | .34 + 2 = 2.34 | 2.34 * 10 * 2 = 234
- 234 / 10 * 3 = .234 | .234 + 1 = 1.234 | 1.234 * 10 * 3 = 1234
-
- Not bad for the top of my head...given more time, i'd think of a better
- way, i'm sure...
-
-